package com.paomi.client.fragment.mine;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.paomi.client.GlideApp;
import com.paomi.client.R;
import com.paomi.client.activity.person.InvitationActivity;
import com.paomi.client.activity.person.MyCardActivity;
import com.paomi.client.activity.person.MyCollectionActivity;
import com.paomi.client.activity.person.MyCommentsActivity;
import com.paomi.client.activity.person.MyOrderActivity;
import com.paomi.client.activity.person.MyPointActivity;
import com.paomi.client.activity.person.PersonMsgActivity;
import com.paomi.client.activity.person.SettingActivity;
import com.paomi.client.activity.person.model.MyOrderNumBean;
import com.paomi.client.activity.person.model.TaskListBean;
import com.paomi.client.activity.person.model.TaskListDetailBean;
import com.paomi.client.activity.vip.MyVipActivity;
import com.paomi.client.base.BaseLCEFragment;
import com.paomi.client.bean.UserInfo;
import com.paomi.client.bean.UserInfoEntity;
import com.paomi.client.bean.UserUtils;
import com.paomi.client.fragment.mine.presenter.MineFraPre;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.utils.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by pc on 2018/10/25
 * Describe:
 * com.paomi.client.fragment
 */
public class MineFragment extends BaseLCEFragment<UserInfo, MineFraPre> {
    @BindView(R.id.textview_title)
    TextView textviewTitle;
    @BindView(R.id.tv_btn_setting)
    TextView tv_btn_setting;
    @BindView(R.id.tv_btn_question)
    TextView tv_btn_question;
    @BindView(R.id.tv_img_arrow)
    TextView tv_img_arrow;
    @BindView(R.id.tv_order_pay)
    TextView tv_order_pay;
    @BindView(R.id.tv_order_all)
    TextView tv_order_all;
    @BindView(R.id.tv_arrow_shop)
    TextView tv_arrow_shop;
    @BindView(R.id.tv_order_delivery)
    TextView tv_order_delivery;
    @BindView(R.id.tv_order_receiving)
    TextView tv_order_receiving;
    @BindView(R.id.tv_arrow_collection)
    TextView tv_arrow_collection;
    @BindView(R.id.tv_arrow_card)
    TextView tv_arrow_card;
    @BindView(R.id.tv_arrow_comment)
    TextView tv_arrow_comment;
    @BindView(R.id.tv_arrow_vip)
    TextView tv_arrow_vip;
    @BindView(R.id.tv_arrow_invitation)
    TextView tv_arrow_invitation;
    @BindView(R.id.tv_arrow_contact)
    TextView tv_arrow_contact;
    @BindView(R.id.tv_sign)
    TextView tv_sign;
    @BindView(R.id.tv_currency_icon)
    TextView tv_currency_icon;

    @BindView(R.id.view_all)
    View view_all;
    @BindView(R.id.view_pay)
    View view_pay;
    @BindView(R.id.view_delivery)
    View view_delivery;
    @BindView(R.id.view_collect)
    View view_collect;

    //正文
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_currency)
    TextView tv_currency;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.ll_rank)
    LinearLayout ll_rank;
    @BindView(R.id.ll_currency)
    LinearLayout ll_currency;
    @BindView(R.id.iv_rank)
    ImageView iv_rank;
    @BindView(R.id.tv_rank)
    TextView tv_rank;

    private final int REQUEST_CODE_ASK_CALL_PHONE = 1;

    public static MineFragment newInstance(String name) {

        Bundle args = new Bundle();
        args.putString("name", name);
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    protected int getFragmentLayoutId() {
        return R.layout.fragment_mine;
    }

    @NonNull
    @Override
    protected RecyclerView createRecycler() {
        return null;
    }

    @Override
    protected int getItemLayout() {
        return 0;
    }

    @Override
    protected void initEmpty(TextView empty) {

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        textviewTitle.setText(getResources().getString(R.string.mine_center));
        initTypeFace();
        tv_sign.setText(getResources().getString(R.string.mine_sign) + "   " + getResources().getString(R.string.sign));
        getPresenter().getOrderNum();
    }

    @OnClick(R.id.ll_comment)
    void toMyComment() {
        Intent i = new Intent(getActivity(), MyCommentsActivity.class);
        startActivity(i);
    }

    @OnClick(R.id.ll_all)
    void toAll() {
        Intent i = new Intent(getActivity(), MyOrderActivity.class);
        i.putExtra("pos", 0);
        startActivity(i);
    }

    @OnClick(R.id.ll_tobe_pay)
    void toPay() {
        Intent i = new Intent(getActivity(), MyOrderActivity.class);
        i.putExtra("pos", 1);
        startActivity(i);
    }

    @OnClick(R.id.ll_delivery)
    void toDelivery() {
        Intent i = new Intent(getActivity(), MyOrderActivity.class);
        i.putExtra("pos", 2);
        startActivity(i);
    }

    @OnClick(R.id.ll_collect)
    void toCollect() {
        Intent i = new Intent(getActivity(), MyOrderActivity.class);
        i.putExtra("pos", 3);
        startActivity(i);
    }

    @OnClick(R.id.ll_collection)
    void toCollection() {
        Intent i = new Intent(getActivity(), MyCollectionActivity.class);
        startActivity(i);
    }

    @OnClick(R.id.ll_person)
    void toPerson() {
        Intent i = new Intent(getActivity(), PersonMsgActivity.class);
        startActivity(i);
    }

    @OnClick(R.id.ll_invitation)
    void invitation() {
        Intent i = new Intent(getActivity(), InvitationActivity.class);
        startActivity(i);
    }

    @OnClick(R.id.ll_card)
    void toCard() {
        Intent i = new Intent(getActivity(), MyCardActivity.class);
        startActivity(i);
    }

    @OnClick(R.id.tv_btn_setting)
    void setting() {
        Intent i = new Intent(getActivity(), SettingActivity.class);
        startActivity(i);
    }

    @OnClick(R.id.tv_sign)
    void toSign() {
        if (tv_sign.getText().equals(getResources().getString(R.string.sign_out))) {
            Util.toast(getActivity(), "您已经签到过了");
            return;
        }
        getPresenter().toSign();
    }

    @OnClick(R.id.ll_currency)
    void toRank() {
        Intent i = new Intent(getActivity(), MyPointActivity.class);
        startActivity(i);
    }
    @OnClick(R.id.lay_call)
    void toCall() {//联系客服
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.CALL_PHONE},
                        REQUEST_CODE_ASK_CALL_PHONE);
            } else {
                Util.callCustomerService(getActivity());
            }
        } else {
            Util.callCustomerService(getActivity());
        }
    }

    @OnClick(R.id.ll_vip)
    void toMyVip() {
        getIntent(MyVipActivity.class);
    }

    @Override
    protected void convert(BaseViewHolder helper, UserInfo item) {

    }

    @Override
    protected void onItemClick(View view, UserInfo item) {

    }

    void initTypeFace() {
        tv_btn_setting.setTypeface(iconfont);
        tv_currency_icon.setTypeface(iconfont);
        tv_sign.setTypeface(iconfont);
        tv_arrow_shop.setTypeface(iconfont);
        tv_btn_question.setTypeface(iconfont);
        tv_img_arrow.setTypeface(iconfont);
        tv_order_pay.setTypeface(iconfont);
        tv_order_all.setTypeface(iconfont);
        tv_order_delivery.setTypeface(iconfont);
        tv_order_receiving.setTypeface(iconfont);
        tv_arrow_collection.setTypeface(iconfont);
        tv_arrow_card.setTypeface(iconfont);
        tv_arrow_comment.setTypeface(iconfont);
        tv_arrow_vip.setTypeface(iconfont);
        tv_arrow_invitation.setTypeface(iconfont);
        tv_arrow_contact.setTypeface(iconfont);
    }

    public void NoLogin() {
        GlideApp.with(getActivity()).load(R.mipmap.img_default_head).into(iv_head);
        tv_name.setText("");
        tv_time.setText("");
        ll_rank.setVisibility(View.GONE);
        ll_currency.setVisibility(View.GONE);
        view_all.setVisibility(View.GONE);
        view_pay.setVisibility(View.GONE);
        view_delivery.setVisibility(View.GONE);
        view_collect.setVisibility(View.GONE);
        tv_sign.setText(getResources().getString(R.string.mine_sign) + "   " + getResources().getString(R.string.sign));
    }

    public String getDateSx() {
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        if (hour >= 6 && hour < 8) {
            return "早上好";
        } else if (hour >= 8 && hour < 11) {
            return "上午好";
        } else if (hour >= 11 && hour < 13) {
            return "中午好";
        } else if (hour >= 13 && hour < 18) {
            return "下午好";
        } else {
            return "晚上好";
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        if (UserUtils.getInstance().getUserInfo1() != null) {
            getPresenter().getUserInfo();
        } else {
            NoLogin();
        }
    }

    @Subscribe
    public void onEvent(Object result) {
        if (result instanceof String) {
            if (result.equals("SignSuccess")) {
                ToastUtil.getToastEmail().ToastSign(getActivity(), null, 1, R.layout.toast_sign, "+20");
                tv_sign.setText(getResources().getString(R.string.sign_out));
                tv_sign.setTextColor(0x55FFFFFF);//00 表示完全透明，ff 表示完全不透明。
            }
        } else if (result instanceof MyOrderNumBean) {
            if (((MyOrderNumBean) result).returnCode.equals("0000")) {
                if (((MyOrderNumBean) result).getReturnData().size() > 0) {
                    view_all.setVisibility(View.VISIBLE);
                    for (int i = 0; i < ((MyOrderNumBean) result).getReturnData().size(); i++) {
                        if (((MyOrderNumBean) result).getReturnData().get(i).getState() == 0) {
                            view_pay.setVisibility(View.VISIBLE);
                        } else if (((MyOrderNumBean) result).getReturnData().get(i).getState() == 1) {
                            view_delivery.setVisibility(View.VISIBLE);
                        } else if (((MyOrderNumBean) result).getReturnData().get(i).getState() == 3) {
                            view_collect.setVisibility(View.VISIBLE);
                        }
                    }
                }

            }
        } else if (result instanceof TaskListBean) {
            if (((TaskListBean) result).returnCode.equals("0000")) {
                List<TaskListDetailBean> list = new ArrayList<>();
                list.addAll(((TaskListBean) result).getReturnData());
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getName().contains("签到")) {
                        if (list.get(i).isComplete()) {
                            tv_sign.setText(getResources().getString(R.string.sign_out));
                            tv_sign.setTextColor(0x55FFFFFF);//00 表示完全透明，ff 表示完全不透明。
                        } else {
                            tv_sign.setText(getResources().getString(R.string.mine_sign) + "   " + getResources().getString(R.string.sign));
                            tv_sign.setTextColor(getResources().getColor(R.color.white));
                        }
                    }
                }
            }
        } else if(result instanceof UserInfoEntity){//刷新个人的数据（主要是会员和积分）
            UserInfoEntity userInfoEntity=(UserInfoEntity)result;
            if(userInfoEntity!=null){
                UserUtils.getInstance().saveUser1(userInfoEntity.getInfo());
            }
            UserInfo info = UserUtils.getInstance().getUserInfo1();
            if (info != null) {
                if (info.getHeadimgurl() != null) {
                    GlideApp.with(getActivity())
                            .asBitmap()
                            .load(info.getHeadimgurl())
                            .placeholder(R.mipmap.img_default_head)
                            .into(iv_head);
                }
                if (info.getUserName() != null) {
                    tv_name.setText(info.getUserName());
                }
                tv_time.setText(getDateSx() + ",");
                ll_currency.setVisibility(View.VISIBLE);
                if (info.getMemberInfo() != null) {
                    if (info.getMemberInfo().getValue() > 0) {
                        tv_currency.setText(getResources().getString(R.string.app_currency_) + info.getMemberInfo().getBalance() + "");
                    } else {
                        tv_currency.setText(getResources().getString(R.string.app_currency_) + "0");
                    }
                    if (info.getMemberInfo().getLevleName() != null && !info.getMemberInfo().getLevleName().equals("")) {
                        ll_rank.setVisibility(View.VISIBLE);
                        if (info.getMemberInfo().getLevleName().equals("黄金")) {
                            Glide.with(this).asBitmap().load(R.mipmap.img_hy_jin).into(iv_rank);
                            ll_rank.setBackground(getResources().getDrawable(R.drawable.circle_btn_ffd231));
                            tv_rank.setText(info.getMemberInfo().getLevleName() + getResources().getString(R.string.vip));
                            tv_rank.setTextColor(getResources().getColor(R.color.color_CF7A00));
                        } else if (info.getMemberInfo().getLevleName().equals("白银")) {
                            Glide.with(this).asBitmap().load(R.mipmap.img_hy_yin).into(iv_rank);
                            ll_rank.setBackground(getResources().getDrawable(R.drawable.circle_btn_c5dbe3));
                            tv_rank.setText(info.getMemberInfo().getLevleName() + getResources().getString(R.string.vip));
                            tv_rank.setTextColor(getResources().getColor(R.color.color_7B8A8F));
                        } else if (info.getMemberInfo().getLevleName().equals("青铜")) {
                            Glide.with(this).asBitmap().load(R.mipmap.img_hy_tong).into(iv_rank);
                            ll_rank.setBackground(getResources().getDrawable(R.drawable.circle_btn_f9bb6c));
                            tv_rank.setText(info.getMemberInfo().getLevleName() + getResources().getString(R.string.vip));
                            tv_rank.setTextColor(getResources().getColor(R.color.color_CF7500));
                        } else if (info.getMemberInfo().getLevleName().equals("钻石")) {
                            Glide.with(this).asBitmap().load(R.mipmap.img_hy_zuanshi).into(iv_rank);
                            ll_rank.setBackground(getResources().getDrawable(R.drawable.circle_btn_3d4343));
                            tv_rank.setText(info.getMemberInfo().getLevleName() + getResources().getString(R.string.vip));
                            tv_rank.setTextColor(getResources().getColor(R.color.text_gray_ee));

                        }
                    }
                }
            }
            getPresenter().getTaskList();

        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Override
    public MineFraPre createPresenter() {
        return new MineFraPre();
    }

    @Override
    public void setData(List<UserInfo> data, boolean pullToRefresh) {
        super.setData(data, pullToRefresh);
        //移除FooterView
        getmAdapterWrapper().setLoadItemVisibility(false);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_ASK_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Util.callCustomerService(getActivity());
            }
        }
    }
}
